package cn.kgc.mcartoon.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Data
public class JWTUtil {

    // 密钥
    private String secretKey = "m-cartoon";

    //单位秒，默认7天
    private long expires = 60*60*24*7;

    /**
     * 生成JWT
     * @param id
     */
    public String createJWT(String id, String subject, Boolean isLogin) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder()
                                .setId(id)
                                .setSubject(subject)
                                .setIssuedAt(now)
                                .signWith(SignatureAlgorithm.HS256,secretKey)
                                .claim("isLogin", isLogin);

        if (expires > 0) {
            // expires乘以1000是毫秒转秒
            builder.setExpiration(new Date(nowMillis + expires*1000));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     * @param jwtToken
     */
    public Claims parseJWT(String jwtToken){
        return Jwts.parser().setSigningKey(secretKey)
                .parseClaimsJws(jwtToken)
                .getBody();
    }

}

